package com.yinhe.music.yhmusic.music;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.request.transition.Transition;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.umeng.analytics.MobclickAgent;
import com.yinhe.music.common.GlideHelper.BitmapTarget;
import com.yinhe.music.common.GlideHelper.GlideHelper;
import com.yinhe.music.common.utils.Md5Utils;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.event.RxbusNullObject;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.adapter.PlayPagerAdapter;
import com.yinhe.music.yhmusic.base.BaseModel;
import com.yinhe.music.yhmusic.base.BasePresenter;
import com.yinhe.music.yhmusic.base.BasePresneterActivity;
import com.yinhe.music.yhmusic.comment.CommentListActivity;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.constants.KeyConstants;
import com.yinhe.music.yhmusic.db.DataBaseAccessor;
import com.yinhe.music.yhmusic.db.bean.SongDBEntity;
import com.yinhe.music.yhmusic.dialog.MusicQualityDialog;
import com.yinhe.music.yhmusic.dialog.more.IMoreDialogContract;
import com.yinhe.music.yhmusic.dialog.more.MoreDialog;
import com.yinhe.music.yhmusic.dialog.more.MoreDialogPresenter;
import com.yinhe.music.yhmusic.enums.PlayModeEnum;
import com.yinhe.music.yhmusic.localmusic.view.LocalMusicDialog;
import com.yinhe.music.yhmusic.log.BlankUtil;
import com.yinhe.music.yhmusic.log.MLog;
import com.yinhe.music.yhmusic.lrc.LrcView;
import com.yinhe.music.yhmusic.model.Music;
import com.yinhe.music.yhmusic.model.MvsInfo;
import com.yinhe.music.yhmusic.model.RadioListInfo;
import com.yinhe.music.yhmusic.radio.RadioActivity;
import com.yinhe.music.yhmusic.service.PlayService;
import com.yinhe.music.yhmusic.utils.FileUtils;
import com.yinhe.music.yhmusic.utils.PlayingCoverLoader;
import com.yinhe.music.yhmusic.utils.Preferences;
import com.yinhe.music.yhmusic.utils.ToastUtils;
import com.yinhe.music.yhmusic.widget.AlbumCoverView;
import com.yinhe.music.yhmusic.widget.CommentView;
import com.yinhe.music.yhmusic.widget.PlayerSeekBar;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.yinhe.music.yhmusic.enums.PlayModeEnum.LOOP;
import static com.yinhe.music.yhmusic.enums.PlayModeEnum.ONE;
import static com.yinhe.music.yhmusic.enums.PlayModeEnum.SHUFFLE;


/**
 * 播放页面
 */
public class PlayingActivity extends BasePresneterActivity implements View.OnClickListener,
        ViewPager.OnPageChangeListener, SeekBar.OnSeekBarChangeListener,
        IMoreDialogContract.IMoreDialogView, PlayingContract.IPlayingView {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.playing_mode)
    ImageView playingmode;
    @BindView(R.id.playing_play)
    ImageView ivPlay;
    @BindView(R.id.playing_list)
    ImageView playlist;
    @BindView(R.id.playing_fav)
    ImageView fav;
    @BindView(R.id.playing_next)
    ImageView ivNext;
    @BindView(R.id.playing_share)
    ImageView share;
    @BindView(R.id.playing_pre)
    ImageView ivPrev;
    @BindView(R.id.comment_view)
    CommentView commentIcon;
    @BindView(R.id.view_pager)
    ViewPager vpPlay;
    @BindView(R.id.play_seek)
    PlayerSeekBar sbProgress;
    @BindView(R.id.music_duration_played)
    TextView tvCurrentTime;

    @BindView(R.id.music_duration)
    TextView tvTotalTime;
    @BindView(R.id.title_songName)
    TextView tvSongName;
    @BindView(R.id.title_singerName)
    TextView tvSongAuthor;

    @BindView(R.id.music_tool)
    LinearLayout mMusicTool;

    private ActionBar abTitle;
    private TextView tvRadioName, tvRadioContent;
    private AlbumCoverView mAlbumCoverView;
    private LrcView mLrcViewSingle, mLrcViewFull;
    private List<View> mViewPagerContent;
    private Music musicInfo;
    private int mLastProgress;
    private boolean isLike;
    private boolean mNeedInit = false;

    MoreDialogPresenter mPresenter;
    PlayingPresenter playingPresenter;

    @Override
    public BasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    public void initPresenter() {
        mPresenter = new MoreDialogPresenter();
        mPresenter.attachModelView(new BaseModel(), this);

        playingPresenter = new PlayingPresenter();
        playingPresenter.attachModelView(new BaseModel(), this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_playing);
        ButterKnife.bind(this);
        RxBus.get().register(this);
        setToolbar();
        updateModeView(PlayModeEnum.valueOf(Preferences.getPlayMode()));
        setListener();
        if (mService != null) {
            init();
        } else {
            mNeedInit = true;
        }
    }

    @Override
    protected void onDestroy() {
        RxBus.get().unregister(this);
        if (playingPresenter != null) {
            playingPresenter.dispose();
            playingPresenter.onDetach();
        }
        super.onDestroy();
    }

    private void setToolbar() {
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            abTitle = getSupportActionBar();
            abTitle.setDisplayHomeAsUpEnabled(true);
            abTitle.setTitle("");
            toolbar.setNavigationIcon(R.drawable.icon_back_black);
            toolbar.setNavigationOnClickListener((v) -> onBackPressed());
        }
    }

    @Override
    public void onPause() {
        if (mAlbumCoverView != null) mAlbumCoverView.pause();
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        initPlay();
    }

    private void init() {
        initViewPager();
        onChange(mService.getPlayingMusic());
    }


    private void initPlay() {
        if (mService != null && ivPlay != null) {
            ivPlay.setImageResource(mService.isPlaying()
                    ? R.drawable.ic_stop
                    : R.drawable.ic_play);
            if (mService.isPlaying()) {
                mAlbumCoverView.start();
            } else {
                mAlbumCoverView.pause();
            }
        }
    }

    @Override
    public void onServiceConnected(PlayService service) {
        super.onServiceConnected(service);
        if (mNeedInit) {
            init();
            mNeedInit = false;
        }
        initPlay();
    }

    private void setListener() {
        sbProgress.setOnSeekBarChangeListener(this);
        vpPlay.setOnPageChangeListener(this);

        ivPlay.setOnClickListener(this);
        ivPrev.setOnClickListener(this);
        ivNext.setOnClickListener(this);
        playlist.setOnClickListener(this);
        fav.setOnClickListener(this);
        playingmode.setOnClickListener(this);
        share.setOnClickListener(this);
        commentIcon.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (mService != null) {
            Music music = mService.getPlayingMusic();
            switch (v.getId()) {
                case R.id.playing_play:
                    play();
                    break;
                case R.id.playing_next:
                    next();
                    break;
                case R.id.playing_pre:
                    prev();
                    break;
                case R.id.playing_fav:
                    setLike(music);
                    break;
                case R.id.playing_mode:
                    updateMode();
                    break;
                case R.id.playing_share:
                    share(music);
                    break;
                case R.id.playing_list:
                    showPlayingList();
                    break;
                case R.id.radio_name:
                    Intent intent = new Intent(this, RadioActivity.class);
                    intent.putExtra("radioid", music.getRadioId());
                    startActivity(intent);
                    break;
                case R.id.comment_view:
                    startCommentView(music);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.playing_menu, menu);
        if (mService == null) {
            menu.getItem(0).setIcon(null);
            return super.onCreateOptionsMenu(menu);
        }

        Music music = mService.getPlayingMusic();
        if (music == null) {
            return super.onCreateOptionsMenu(menu);
        }
        if (music.isRadio()) menu.getItem(0).setIcon(null);

        SongDBEntity songDBEntity = DataBaseAccessor.getInstance().getSongById(music.songId);
        if (songDBEntity == null) {
            return super.onCreateOptionsMenu(menu);
        }
        if (songDBEntity.isSyn()) menu.getItem(0).setIcon(null);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        if (mService == null) {
            return super.onOptionsItemSelected(item);
        }
        Music music = mService.getPlayingMusic();
        if (music.isRadio()) {
            return super.onOptionsItemSelected(item);
        }

        if (item.getItemId() != R.id.menu_more) {
            return super.onOptionsItemSelected(item);
        }
        SongDBEntity songDBEntity = DataBaseAccessor.getInstance().getSongById(music.songId);
        if (songDBEntity != null && songDBEntity.isSyn()) {
            LocalMusicDialog dialog = LocalMusicDialog.newInstance(music, IConstants.LOCAL_MUSIC, null);
            dialog.show(getSupportFragmentManager(), KeyConstants.KEY_LOCAL_MUSIC_DIALOG);
        } else {
            MoreDialog.newInstance(music, 0, IConstants.PLAYING_MUSIC_MANAGER).show(getSupportFragmentManager(), "MoreDialog");
        }

        return super.onOptionsItemSelected(item);
    }


    private void initViewPager() {
        View coverView = LayoutInflater.from(this).inflate(R.layout.fragment_play_page_cover, null);
        View lrcView   = LayoutInflater.from(this).inflate(R.layout.fragment_play_page_lrc, null);
        View radioView = LayoutInflater.from(this).inflate(R.layout.fragment_play_page_radio, null);

        mAlbumCoverView = coverView.findViewById(R.id.album_cover_view);
        mLrcViewSingle  = coverView.findViewById(R.id.lrc_view_single);
        mLrcViewFull    = lrcView.findViewById(R.id.lrc_view_full);
        tvRadioName     = radioView.findViewById(R.id.radio_name);
        tvRadioContent  = radioView.findViewById(R.id.radio_content);
        tvRadioName.setOnClickListener(this);

        mViewPagerContent = new ArrayList<>();
        mViewPagerContent.add(coverView);

        if (mService == null) {
            return;
        }
        Music music = mService.getPlayingMusic();
        if (music == null) {
            ToastUtils.show(R.string.playing_music_null);
            finish();
        }
        if (music.isRadio()) {
            mViewPagerContent.add(radioView);
        } else {
            mViewPagerContent.add(lrcView);
        }
        vpPlay.setAdapter(new PlayPagerAdapter(mViewPagerContent));
    }

    /**
     * 更新播放进度
     */
    @Override
    public void onPublish(int progress) {
        super.onPublish(progress);

        sbProgress.setProgress(progress);

        if (mLrcViewSingle.hasLrc()) {
            mLrcViewSingle.updateTime(progress);
            mLrcViewFull.updateTime(progress);
        }
        //更新当前播放时间
        if (progress - mLastProgress >= 1000) {
            tvCurrentTime.setText(formatTime(progress));
            mLastProgress = progress;
        }
    }

    @Override
    public void onChange(Music music) {
        super.onChange(music);
        if (music == null) {
            ToastUtils.show(R.string.playing_music_null);
            return;
        }
        boolean isLocal = DataBaseAccessor.getInstance().isExistSongDBId((int) music.songId);
        initPlay();
        invalidateOptionsMenu();
        if (!music.isRadio() && !isLocal) {
            mPresenter.getMusicInfo(music);
        }
        if (music.isRadio()) {
            commentIcon.setUnreadCount(music.getCommentNum());
            playingPresenter.getRadioInfo(music.getRadioId());
        }
        initPlayingView(music);
    }

    private void setCover(final Music music) {
        if (TextUtils.isEmpty(music.getCoverUri())) {
            mAlbumCoverView.setCoverBitmap(PlayingCoverLoader.getInstance().getDefaultRoundImage());
            return;
        }
        Bitmap bitmap = PlayingCoverLoader.getInstance().getRoundImage(music.getCoverUri());
        if (bitmap == null) {
            GlideHelper.setCircleImageResource(this, music.getCoverUri(), new BitmapTarget() {
                @Override
                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                if (resource != null) {
                    // Bitmap cover = ImageUtils.resizeImage(resource, ToolUtils.dip2px(PlayingActivity.this, 230), ToolUtils.dip2px(PlayingActivity.this, 230));
                    mAlbumCoverView.setCoverBitmap(resource);
                    PlayingCoverLoader.getInstance().setRoundImage(music.getCoverUri(), resource);
                } else {
                    mAlbumCoverView.setCoverBitmap(PlayingCoverLoader.getInstance().getDefaultRoundImage());
                }
                }
            });
            return;
        }
        mAlbumCoverView.setCoverBitmap(bitmap);
    }


    private void setLrc(final Music music) {
        if (TextUtils.isEmpty(music.getLyric())) {
            loadEmptyLrc();
            return;
        }

        ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();
        singleThreadPool.execute(() -> {
            String name = Md5Utils.getMD5(music.getLyric());
            if (TextUtils.isEmpty(name)) {
                loadEmptyLrc();
                return;
            }
            String lrcPath = FileUtils.getLrcPath(name);
            File f = new File(lrcPath);
            if (!f.exists() && !BlankUtil.isBlank(music.getLyric())) {
                FileUtils.writeContentFromUrl(music.getLyric(), lrcPath, music.getLyricCode());
            }
            loadLrc(lrcPath);
        });
    }

    private void loadEmptyLrc() {
        mHandler.post(() -> {
            mLrcViewSingle.loadEmptyLrc();
            mLrcViewFull.loadEmptyLrc();
        });
    }

    private void loadLrc(String path) {
        final File file = new File(path);
        mHandler.post(() -> {
            mLrcViewSingle.loadLrc(file);
            mLrcViewFull.loadLrc(file);
        });
    }


    private void startCommentView(Music music) {
        Intent it = new Intent(this, CommentListActivity.class);
        it.putExtra("commentType", music.isRadio()
                ? IConstants.RADIO_SONG
                : IConstants.SONG);
        it.putExtra("name", music.getSongName());
        it.putExtra("artist", music.getSingerName());
        it.putExtra("cover", music.getCoverUri());
        it.putExtra("id", (int) music.getSongId());
        startActivity(it);
    }

    private void play() {
        if (mService == null) return;
        ivPlay.setImageResource(mService.isPause()
                ? R.drawable.ic_play
                : R.drawable.ic_stop);
        mService.playPause();
    }

    private void next() {
        if (mService == null) return;
        mService.next();
        onChange(mService.getPlayingMusic());
    }

    private void prev() {
        if (mService == null) return;
        mService.prev();
        onChange(mService.getPlayingMusic());
    }

    private void share(Music music) {
        if(music == null) return;
        playingPresenter.getShareInfo(music.isRadio()
                ? IConstants.RADIO_SONG
                : IConstants.SONG, (int) music.getSongId(), this);
    }

    private void setLike(Music music) {
        if (Preferences.getLoginSn().isEmpty()) {
            startHome();
            return;
        }
        if (music == null) {
            return;
        }
        int id = (int) music.getSongId();
        playingPresenter.setFav(id, isLike);
    }

    private void initPlayingView(Music music) {
        setName(music);
        setCover(music);

        if (mService == null) return;
        setProgress();
        if (mService.isPlaying()) {
            ivPlay.setSelected(true);
            mAlbumCoverView.start();
        } else {
            ivPlay.setSelected(false);
            mAlbumCoverView.pause();
        }

        SongDBEntity songDBEntity = DataBaseAccessor.getInstance().getSongById(music.songId);
        mMusicTool.setVisibility(songDBEntity != null && songDBEntity.isSyn()
                ? View.INVISIBLE
                : View.VISIBLE);

        if (music.isRadio()) {
            fav.setVisibility(View.GONE);
        }
    }

    private void initQuality(Music music) {
        if (music.isRadio()) {
            mLrcViewSingle.setVisibility(View.GONE);
            fav.setVisibility(View.GONE);
        } else {
            initQualityView(music);
            mLrcViewSingle.setVisibility(View.VISIBLE);
            fav.setVisibility(View.VISIBLE);
            share.setVisibility(View.VISIBLE);
        }
    }

    private void initQualityView(Music music) {
        switch (Preferences.getQuality()) {
            case IConstants.Common:
//                quality.setImageResource(R.drawable.ic_regular_long);
                break;
            case IConstants.HQ:
                if (music.getQualityLevel().compareTo(IConstants.HQ) >= 0) {
//                    quality.setImageResource(R.drawable.ic_hq_long);
                } else {
                    Preferences.setQuality(IConstants.Common);
//                    quality.setImageResource(R.drawable.ic_regular_long);
                }
                break;
            case IConstants.SQ:
                if (music.getQualityLevel().compareTo(IConstants.SQ) >= 0) {
//                    quality.setImageResource(R.drawable.ic_sq_long);
                } else {
                    Preferences.setQuality(IConstants.Common);
//                    quality.setImageResource(R.drawable.ic_regular_long);
                }
                break;
            default:
                break;
        }
    }

    private void setName(Music music) {
        tvSongName.setText(music.getSongName());
        tvSongName.setSelected(true);
        tvSongAuthor.setText("—  " + music.getSingerName() + "  —");
    }

    private void setProgress() {
        int max = (int) mService.getDuration();
        if (max <= 1000) {
            max = 200000;
        }
        sbProgress.setMax(max);
        sbProgress.setProgress(0);
        mLastProgress = 0;
        tvCurrentTime.setText(R.string.play_time_start);
        tvTotalTime.setText(formatTime((mService.getDuration())));
        onPublish(mService.getPlayingProgress());
    }

    private void updateMode() {
        PlayModeEnum mode = PlayModeEnum.switchPlayMode();
        updateModeView(mode);
    }

    public void updateModeView(PlayModeEnum mode) {
        if (mode == LOOP) {
            playingmode.setImageResource(R.drawable.ic_order_playback_white);
        } else if (mode == ONE) {
            playingmode.setImageResource(R.drawable.ic_single_play_white);
        } else if (mode == SHUFFLE) {
            playingmode.setImageResource(R.drawable.ic_random_play_white);
        }
    }

    @Override
    public void updateMusicInfoUI(Music music) {
        musicInfo = music;
        setLrc(music);
        commentIcon.setUnreadCount(musicInfo.getCommentNum());
        initQuality(musicInfo);
        if (musicInfo.getCollectStatus() == 0) {
            isLike = false;
            fav.setImageResource(R.drawable.ic_heart);
        } else {
            isLike = true;
            fav.setImageResource(R.drawable.ic_heart_red_singer);
        }
    }

    @Override
    public void updateMvInfoUI(MvsInfo mvsInfo) {

    }

    @Override
    public void setVipBuyUI() {

    }

    @Override
    public void updateFavStatus() {
        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_DUM_NORMAL);
        if (isLike) {
            isLike = false;
            fav.setImageResource(R.drawable.ic_heart);
        } else {
            isLike = true;
            fav.setImageResource(R.drawable.ic_heart_red_singer);
        }
    }

    @Override
    public void setRadioIntroUI(RadioListInfo radioListInfo) {
        String name = "电台：" + radioListInfo.getRadioName();
        String detail = "电台详情：" + radioListInfo.getIntro();
        tvRadioName.setText(name);
        tvRadioContent.setText(detail);
    }

    @Override
    public void onPlayerPause() {
        super.onPlayerPause();
        ivPlay.setImageResource(R.drawable.ic_play);
        mAlbumCoverView.pause();
    }

    @Override
    public void onPlayerResume() {
        super.onPlayerResume();
        ivPlay.setImageResource(R.drawable.ic_stop);
        mAlbumCoverView.start();
        if (mService != null) tvTotalTime.setText(formatTime(mService.getDuration()));
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
//        ilIndicator.setCurrent(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if (mService != null && (mService.isPlaying() || mService.isPause())) {
            int progress = seekBar.getProgress();
            mService.seekTo(progress);
            mLrcViewSingle.onDrag(progress);
            mLrcViewFull.onDrag(progress);
            tvCurrentTime.setText(formatTime(progress));
            mLastProgress = progress;
        } else {
            seekBar.setProgress(0);
            play();
        }
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.Playing.CHANGE_PLAYING_MODE)
    )
    public void onRxbusPlayingMode(PlayModeEnum playModeEnum) {
        updateModeView(playModeEnum);
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.Music.CLEAR_PLAYLIST)
    )
    public void onRxbusPlayingMode(RxbusNullObject rxbusNullObject) {
        finish();
    }
}

